package com.atguigu.binarySearch;

/**
 * 二分查找
 */
public class BinarySearch {

    public static int binarySearch(int[] arrays, int target) {
        //左
        int left = 0;

        //右
        int right = arrays.length - 1;

        //循环直到左>右停止
        while (left < right) {

            //中间
            int middle = left + (right - left) / 2;

            //中间值与目标值相等时找到返回
            if (arrays[middle] == target) {
                return middle;

                //中间值比目标值大时
            } else if (arrays[middle] > target) {

                //右等于中间值-1（砍半）
                right = middle - 1;
            } else {
                //否则（中间值比目标值小） 左等于中间值+1
                left = middle + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arrays = new int[]{1, 11, 22, 33, 44, 99, 102};
        int target = 99;

        System.out.println(binarySearch(arrays, target));
    }
}
